<template>
	<view class="JGoodsArr">
		<!-- 瀑布流容器 -->
		<view class="waterfall-container" :style="waterfallStyle">
			<view class="waterfall-column" v-for="(column, columnIndex) in columns" :key="columnIndex">
				<view class="goods-card" v-for="(item, index) in column" :key="item.id || index" @click="goToDetail(item)">
					<view class="goods-image-container">
						<image class="goods-image" :src="item.image" mode="aspectFill" lazy-load="true"></image>
						<view class="stock-overlay" v-if="item.stock !== undefined">
							<text class="stock-text">仅剩{{ item.stock }}件</text>
						</view>
					</view>

					<view class="goods-content">
						<text class="goods-title">{{ item.id }}{{ item.name }}</text>
						<!-- <view class="goods-labels" v-if="item.labels && item.labels.length">
							<text class="label" v-for="label in item.labels" :key="label.type" :class="'label-' + label.type">
								{{ label.text }}
							</text>
						</view> -->
						<JWeightPrice
							:price="item.price"
							:weight="item.weight"
							weightColor="#666"
							unitPriceColor="#fa436a"
							textSize="24rpx"
							backgroundColor="#f8f9fa"
							padding="8rpx 12rpx"
							borderRadius="8rpx"
						/>
						<view class="goods-price">
							<view class="price-section">
								<JPrice
									:price="item.price"
									:originalPrice="item.originalPrice"
									priceColor="#fa436a"
									originalPriceColor="#999"
									integerSize="40rpx"
									decimalSize="24rpx"
									symbolSize="24rpx"
								/>
							</view>
							<view class="cart-section">
								<JCartButton :goodsItem="item" @success="handleAddToCartSuccess" @error="handleAddToCartError" />
							</view>
						</view>

						<!-- <view class="goods-tags" v-if="item.tags && item.tags.length">
						<text class="tag" v-for="tag in item.tags" :key="tag">{{ tag }}</text>
					</view> -->

						<view class="sales-info-fixed">
							<!-- <JShopInfo
								:shopName="item.shopName"
								:shopLink="item.shopLink"
								backgroundColor="transparent"
								margin=""
								iconColor="#333"
								iconSize="24rpx"
								shopNameColor="#333"
								shopNameSize="24rpx"
								shopNameWeight="400"
								clickableColor="#333"
								@shopClick="goToShop"
							/> -->
							<JSalesCount :sales="item.sales" textColor="#999" textSize="24rpx" fontWeight="400" />
						</view>
					</view>
				</view>
			</view>
		</view>
	</view>
</template>

<script>
export default {
	name: 'JGoodsArr',
	props: {
		goodsList: {
			type: Array,
			default: () => []
		},
		columnCount: {
			type: Number,
			default: 2
		},
		hasMore: {
			type: Boolean,
			default: true
		}
	},
	data() {
		return {
			loading: false,
			columns: []
		};
	},
	computed: {
		waterfallStyle() {
			return {
				columnCount: this.columnCount
			};
		}
	},
	watch: {
		goodsList: {
			handler() {
				this.distributeGoods();
			},
			immediate: true,
			deep: true
		}
	},
	methods: {
		distributeGoods() {
			// 重置列数据
			this.columns = Array.from({ length: this.columnCount }, () => []);

			// 记录每列的高度
			const columnHeights = Array.from({ length: this.columnCount }, () => 0);

			// 智能分配商品到各列（选择最短的列）
			this.goodsList.forEach((item, index) => {
				// 找到高度最小的列
				const shortestColumnIndex = columnHeights.indexOf(Math.min(...columnHeights));

				// 将商品添加到最短的列
				this.columns[shortestColumnIndex].push(item);

				// 估算商品高度（可以根据实际需求调整）
				const estimatedHeight = this.estimateItemHeight(item);
				columnHeights[shortestColumnIndex] += estimatedHeight;
			});

			// 调试信息（开发时可以查看分配情况）
			if (process.env.NODE_ENV === 'development') {
				console.log('瀑布流分配结果:', {
					columnHeights,
					columns: this.columns.map((col, index) => ({
						column: index,
						count: col.length,
						height: columnHeights[index]
					}))
				});
			}
		},

		// 估算商品项高度
		estimateItemHeight(item) {
			// 基础高度：图片 + 内容区域
			// 图片现在是1:1比例，高度等于容器宽度，这里用固定值估算
			let height = 200; // 图片固定高度（1:1比例）

			// 根据标题长度调整高度
			const titleLength = item.name ? item.name.length : 0;
			if (titleLength > 30) {
				height += 60; // 标题很长时增加高度
			} else if (titleLength > 20) {
				height += 40; // 标题较长时增加高度
			} else {
				height += 30; // 标题较短时
			}

			// 价格区域高度
			height += 50;

			// 根据是否有净重信息调整高度
			if (item.weight) {
				height += 40;
			}

			// 根据是否有店铺信息调整高度
			if (item.shopName) {
				height += 40;
			}

			// 根据标签数量调整高度
			if (item.tags && item.tags.length > 0) {
				height += 30;
			}

			// 底部购物车区域高度
			height += 50;

			return height;
		},
		// 跳转到店铺
		goToShop(item) {
			console.log('跳转到店铺:', item.shopName, item.shopLink);
			// 这里可以跳转到店铺页面
			this.$emit('shopClick', item);
		},
		// 添加购物车成功
		handleAddToCartSuccess(item) {
			console.log('商品已添加到购物车:', item);
			// 这里可以显示成功提示或更新购物车数量
			this.$emit('addToCartSuccess', item);
		},
		// 添加购物车失败
		handleAddToCartError(error) {
			console.error('添加购物车失败:', error);
			// 这里可以显示错误提示
			this.$emit('addToCartError', error);
		},
		goToDetail(item) {
			console.log('查看商品详情:', item);
			// 这里可以跳转到商品详情页
			this.$emit('goodsClick', item);
		},
		loadMore() {
			if (this.loading) return;

			this.loading = true;
			console.log('加载更多商品');

			// 模拟加载延迟
			setTimeout(() => {
				this.loading = false;
				this.$emit('loadMore');
			}, 1000);
		}
	}
};
</script>

<style lang="less">
.JGoodsArr {
	@spacing: 20rpx;
	padding: @spacing;
	// 瀑布流容器
	.waterfall-container {
		display: flex;
		gap: @spacing;
	}

	// 瀑布流列
	.waterfall-column {
		flex: 1;
		display: flex;
		flex-direction: column;
		gap: @spacing;
	}

	// 商品卡片
	.goods-card {
		background: #fff;
		border-radius: 12rpx;
		overflow: hidden;
		// box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.1);
		transition: all 0.3s ease;
		position: relative;

		.sales-info-fixed {
			display: flex;
			// align-items: flex-end;
			align-items: center;
			justify-content: space-between;
			padding-bottom: 10rpx;
			// margin-top: 10rpx;
			padding-top: 10rpx;
		}

		.goods-image-container {
			border-radius: 12rpx;
			overflow: hidden;
			position: relative;
			width: 100%;
			height: 0;
			padding-bottom: 100%; /* 1:1 宽高比 */
		}

		.goods-image {
			position: absolute;
			top: 0;
			left: 0;
			width: 100%;
			height: 100%;
			display: block;
			object-fit: cover;
		}

		.stock-overlay {
			position: absolute;
			bottom: 0;
			left: 0;
			right: 0;
			background: rgba(36, 110, 249, 0.6);
			text-align: center;
			display: flex;
			justify-content: center;
			align-items: center;
			height: 40rpx;
			.stock-text {
				color: #fff;
				font-size: 24rpx;
				line-height: 1;
				font-weight: 400;
			}
		}

		.goods-content {
			padding: 10rpx 15rpx 0;
			.goods-title {
				font-size: 28rpx;
				color: #000;
				line-height: 1.4;
				display: -webkit-box;
				-webkit-box-orient: vertical;
				-webkit-line-clamp: 2;
				line-clamp: 2;
				overflow: hidden;
				margin-bottom: 10rpx;
			}

			.goods-labels {
				display: flex;
				flex-wrap: wrap;
				gap: 6rpx;
				margin-bottom: 10rpx;

				.label {
					font-size: 20rpx;
					padding: 4rpx 8rpx;
					border-radius: 4rpx;
					font-weight: 500;
					line-height: 1;

					&.label-limit {
						background: #fff2e8;
						color: #ff6b35;
						border: 1rpx solid #ff6b35;
					}

					&.label-min {
						background: #e8f4fd;
						color: #246ef9;
						border: 1rpx solid #246ef9;
					}

					&.label-multiple {
						background: #f0f9ff;
						color: #0ea5e9;
						border: 1rpx solid #0ea5e9;
					}

					&.label-special {
						background: #fef3c7;
						color: #f59e0b;
						border: 1rpx solid #f59e0b;
					}

					&.label-discount {
						background: #fce7f3;
						color: #ec4899;
						border: 1rpx solid #ec4899;
					}
				}
			}

			.goods-price {
				display: flex;
				justify-content: space-between;
				align-items: center;
				margin-bottom: 10rpx;

				.price-section {
					flex: 1;
				}

				.cart-section {
					margin-left: 20rpx;
					flex-shrink: 0;
				}
			}

			.goods-tags {
				display: flex;
				flex-wrap: wrap;
				gap: 8rpx;

				.tag {
					background: #f0f0f0;
					color: #666;
					font-size: 20rpx;
					padding: 4rpx 8rpx;
					border-radius: 4rpx;
				}
			}
		}
	}
}
</style>
